/**
 * 
 */
package com.zhisheng.core.security.support;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.security.context.SecurityContextHolder;

import com.zhisheng.core.security.entity.Resource;
import com.zhisheng.core.security.entity.User;



/**
 * @author pcwang
 * 
 */
public class SecurityUserHolder {

	/**
	 * Returns the current user
	 * 
	 * @return
	 */
	public static User getCurrentUser() {
		return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}

	/**
	 * Returns the current role menus
	 * 
	 * @return
	 */
	public static List<Resource> getCurrentMenuResources() {
		List<Resource> resources = new ArrayList<Resource>();
		Map<String, List<Resource>> roleResources = getCurrentUser().getRoleResources();
		for (Iterator<Map.Entry<String, List<Resource>>> iter = roleResources.entrySet().iterator(); iter.hasNext();) {
			Map.Entry<String, List<Resource>> entry = iter.next();
			if (entry.getKey().endsWith("_MENU")) {
				resources.addAll(entry.getValue());
			}
		}
		return resources;
	}

	/**
	 * Returns the current role submenus
	 * 
	 * @return
	 */
	public static List<Resource> getCurrentSubmenuResources() {
		List<Resource> resources = new ArrayList<Resource>();
		Map<String, List<Resource>> roleResources = getCurrentUser().getRoleResources();
		for (Iterator<Map.Entry<String, List<Resource>>> iter = roleResources.entrySet().iterator(); iter.hasNext();) {
			Map.Entry<String, List<Resource>> entry = iter.next();
			if (entry.getKey().endsWith("_SUBMENU")) {
				resources.addAll(entry.getValue());
			}
		}
		return resources;
	}

	/**
	 * return the current user name .
	 * 
	 * @return
	 */
	public static String getCurrentUserName() {
		return getCurrentUser().getName();
	}

}
